import React, { PureComponent } from 'react';
import { FirstHeaderC, performanceAnalysisExport, PrimaryC, PrimaryTextC } from '../../../comps';
import { message } from 'antd';
import { connect } from 'dva';
import header from '../../../assets/busi/performanceAnalysis/profitOverview/header.png';
import headerRed from '../../../assets/busi/performanceAnalysis/profitOverview/headerRed.png';
import headerDarkBlue from '../../../assets/busi/performanceAnalysis/profitOverview/headerDarkBlue.png';
import style from './index.less';
import defaultImg from '../../../assets/busi/performanceAnalysis/profitOverview/default.png';
import defaultImgSelect from '../../../assets/busi/performanceAnalysis/profitOverview/default_select.png';
import redImg from '../../../assets/busi/performanceAnalysis/profitOverview/red.png';
import redImgSelect from '../../../assets/busi/performanceAnalysis/profitOverview/red_select.png';
import darkBlueImg from '../../../assets/busi/performanceAnalysis/profitOverview/darkBlue.png';
import darkBlueImgSelect from '../../../assets/busi/performanceAnalysis/profitOverview/darkBlue_select.png';
import uuid from 'es6-uuid';
import { routerRedux } from 'dva/router';
import { namespace } from '@/src/newModels/leverageAnalysis/PortfolioManageLeverageAnalysisM';

class DrawBoardC extends React.Component {
  state = {
    imgObject: {
      defaultImg,
      defaultImgSelect,
      redImg,
      redImgSelect,
      darkBlueImg,
      darkBlueImgSelect,
    },
    colorMenu: [
      {
        key: 'default',
        selected: true,
      },
      {
        key: 'red',
        selected: false,
      },
      {
        key: 'darkBlue',
        selected: false,
      },
    ],
    colorType: 'default', // 默认蓝色
    staticData: '',
  };

  componentDidMount() {
    if (this.props.searchObj && this.props.searchObj.portfolioCode) {
      this.getLeverageDetailResults(JSON.parse(JSON.stringify(this.props.searchObj).replace(/beginDate/g, 'startDate')));
      this.getLabelSetData();
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.searchObj) !== JSON.stringify(this.props.searchObj)) {
      this.getLeverageDetailResults(JSON.parse(JSON.stringify(nextProps.searchObj).replace(/beginDate/g, 'startDate')));
      this.getLabelSetData();
    }
  }

  // 快捷跳转点击事件
  handleOnChangePage = (e) => {
    this.props.searchObj.codeKey = this.props.codeKey;
    sessionStorage.setItem('searchObj', JSON.stringify(this.props.searchObj));
    if (e === '2000') {
      this.props.dispatch(routerRedux.push(`/performanceAnalysis/yieldPerformance`));
    } else if (e === '3000') {
      this.props.dispatch(routerRedux.push(`/performanceAnalysis/netValueAnalysis`));
    } else if (e === '4000') {
      this.props.dispatch(routerRedux.push(`/performanceAnalysis/assetDeploy`));
    } else if (e === '5000') {
      this.props.dispatch(routerRedux.push(`/performanceAnalysis/profitAndLossAnalysis`));
    } else if (e === '6000') {
      this.props.dispatch(routerRedux.push(`/performanceAnalysis/tradeAnalysisNew`));
    }
  };

  // 根据树形结构，生成面板内容(对应多个模块)
  renderContent = () => {
    const { searchObj } = this.props;
    const data = this.formatData();
    if (data && data.length > 0) {
      const comps = []; // 存放模板选中的选项 按顺序平铺
      data.map((item) => {
        // 给每个一级元素 加一个标题 component为数组元素 封面不需要加标题
        if (item.key != '0000')
          comps.push({
            key: `${item.key}_0`,
            component: [
              (props) => {
                if (item.title === '收益率表现' || item.title === '净值分析' || item.title === '资产配置' || item.title === '盈亏分析' || item.title === '交易分析') {
                  return (
                    <div className={style.titleAddButton}>
                      <FirstHeaderC {...props} title={item.title} colorType={this.state.colorType} />
                      <PrimaryTextC
                        style={{ visibility: this.state.exportLoading ? 'hidden' : 'visible' }}
                        title={'快捷跳转'}
                        onClick={() => {
                          this.handleOnChangePage(item.key);
                        }}
                      />
                    </div>
                  );
                } else {
                  return <FirstHeaderC {...props} title={item.title} colorType={this.state.colorType} />;
                }
              },
            ],
          });
        if (item.children && item.children.length) {
          item.children.forEach((x) => {
            // key后加subIndex，是因为有些左侧菜单对应右侧多个元素
            x.component?.map((component, subIndex) => {
              comps.push({ key: `${x.key}_${subIndex}`, component: [component] });
            });
          });
        } else if (item.component) {
          comps.push({ key: item.key, component: item.component });
        }
      });
      /* id={`${this.props.drawingBoardID}_${item.key}`}
        是因为有些左侧菜单对应右侧多个元素，每个元素是编号是“菜单标号+序号”（如：1001对应10010、10011、10012），选中左侧，定位在第一个元素上 */
      return comps.map((item, i) => (
        <div name={item.title} id={`${this.props.drawingBoardID}_${item.key}`} key={`${this.props.drawingBoardID}_${item.key}`} style={{ marginTop: '16px' }}>
          <div name='performanceAnalysisReport'>
            {item.component.map((x, index) => {
              return x({
                onChange: this.settingData,
                onRef: (ref) => {
                  this.state[item.key] = ref;
                },
                searchData: { ...searchObj, portfolioName: undefined },
                key: item.key,
                id: item.key,
                colorType: this.state.colorType,
              });
            })}
          </div>
        </div>
      ));
    }
  };

  // settingData
  settingData = (args, ref) => {
    this.state[ref]?.changeData(args);
  };

  // 获取标签设置数据
  getLabelSetData = () => {
    this.props.dispatch({
      type: `${namespace}/queryLabelSetData`,
      payload: {},
      callback: (res) => {
        this.setState({ newLabelSetData: [...res.dataSource] }, () => {
          const { newLabelSetData, averageLeverage, productType } = this.state;
          const newLabelSetDataDetail = newLabelSetData && newLabelSetData.find((item) => item.productType === productType);
          if (newLabelSetDataDetail) {
            const { highCriticalValue } = newLabelSetDataDetail;
            if (
              (productType === '1' && averageLeverage >= highCriticalValue) ||
              (productType === '2' && averageLeverage >= highCriticalValue) ||
              (productType === '3' && averageLeverage >= highCriticalValue)
            ) {
              this.setState({
                staticData: '高',
              });
            } else {
              this.setState({
                staticData: '',
              });
            }
          }
        });
      },
    });
  };

  // 获取杠杆率标签数据
  getLeverageDetailResults = (searchObj) => {
    const obj = {
      startDate: searchObj.startDate,
      endDate: searchObj.endDate,
      productcode: searchObj.portfolioCode,
    };
    this.props.dispatch({
      type: `${namespace}/queryLeverageDetailResults`,
      payload: { ...obj },
      callback: (res) => {
        this.setState(
          {
            averageLeverage: res.dataSource[0].averageLeverage,
            productType: res.dataSource[0].productType,
          },
          () => {
            this.getLabelSetData();
          },
        );
      },
    });
  };

  formatData = () => {
    const { treeData, list, selectModule } = this.props;
    let listAfter;
    const { staticData } = this.state;

    if (selectModule === 'db6d084927944eab84171f38fc9c550f' && staticData !== '高') {
      listAfter = list.filter((item) => item !== '1002');
    } else if (selectModule === 'db6d084927944eab84171f38fc9c550f' && staticData === '高') {
      if (list.includes('1002')) {
        listAfter = list;
      } else {
        list.push('1002');
        listAfter = list;
      }
    } else {
      listAfter = list;
    }
    // const listClone = staticData && staticData === '高' ? (selectModule === 'db6d084927944eab84171f38fc9c550f' ? (list.includes('1002') ? list : list.push('1002')) : list) : list;

    const result = treeData.map((node) => node);
    for (let i = 0; i < result.length; i++) {
      // 树形结构转化为列表
      if (!result[i].children) continue;
      const list = result[i].children.map((node) => ((node.parentId = result[i].key), node));
      result.splice(i + 1, 0, ...list);
    }
    return this.listToTree(listAfter, _.cloneDeep(result));
  };

  listToTree = (data, treeData) => {
    // 转化成以模板id 为key 对应数值为元素本身  对象{1000:{},1001:{}}
    const info = treeData.reduce((map, node) => ((map[node.key] = node), (node.children = []), map), {});
    const temp = [];
    treeData.map((node) => {
      data?.map((x) => {
        if (x == node.key) {
          if (info[node.parentId]) {
            // 有第二级菜单 取其第一级菜单并存入在children里
            if (info[node.parentId].children) {
              info[node.parentId].children.push(node);
            }
            const arr = temp.filter((item) => item.key == node.parentId);
            if (!arr.length) temp.push(info[node.parentId]);
          } else {
            // 只有第一级
            const arr = temp.filter((item) => item.key == x);
            if (!arr.length) temp.push(info[node.key]);
          }
        }
      });
    });
    return temp;
  };

  // 浏览器检查
  is360Chrome = () => {
    const uas = navigator.userAgent.split(' ');
    const result = false;
    // 排除ua自带标志的双核浏览器, 余下chrome, chromium及360浏览器
    if (uas[uas.length - 1].indexOf('Safari') == -1) {
      return result;
    }
    for (const key in navigator.plugins) {
      if (!Object.prototype.hasOwnProperty.call(navigator.plugins, key)) {
        continue;
      }
      // np-mswmp.dll文件在chromium及chrome未查询到
      if (navigator.plugins[key].filename === 'np-mswmp.dll') {
        return true;
      }
    }
    return result;
  };

  detectZoom = () => {
    let ratio = 0;
    const { screen } = window;
    const ua = navigator.userAgent.toLowerCase();

    if (ua.indexOf('Mac OS X') || ua.indexOf('Mac')) {
      ratio = window.outerWidth / window.innerWidth;
    } else if (window.devicePixelRatio !== undefined) {
      ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
      if (screen.deviceXDPI && screen.logicalXDPI) {
        ratio = screen.deviceXDPI / screen.logicalXDPI;
      }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
      ratio = window.outerWidth / window.innerWidth;
    }
    if (ratio) {
      ratio = Math.round(ratio * 100);
    }
    return ratio;
  };

  // 导出响应
  onExportpdf = () => {
    const {
      searchObj: { portfolioCode, portfolioName, beginDate, endDate },
    } = this.props;
    // 检查页面是否有缩放
    if (this.is360Chrome()) {
      // 360浏览器特殊处理
      if (!(Math.abs(this.detectZoom() - 100) < 5)) {
        // 去除loading状态
        this.props.onDownloading && this.props.onDownloading(false);
        this.setState({
          start: false,
        });
        message.warning('请将页面缩放比例设置为100%后再进行导出！');
        return;
      }
    } else if (this.detectZoom() !== 100) {
      // 去除loading状态
      this.props.onDownloading && this.props.onDownloading(false);
      this.setState({
        start: false,
      });
      message.warning('请将页面缩放比例设置为100%后再进行导出！');
      return;
    }

    this.setState({ exportLoading: true });
    const pdf = new performanceAnalysisExport();
    pdf.savePDF('performanceAnalysisReportId', 'performanceAnalysisReport', `${portfolioCode}-${portfolioName}(${beginDate}~${endDate})`, (tyep) => {
      this.setState({ exportLoading: false });
    });
  };

  // 模板颜色变化
  colorChange = (obj) => {
    const { colorMenu } = this.state;
    colorMenu.map((item) => {
      if (item.key == obj.key) {
        item.selected = true; // 永远有一个是选中状态
      } else {
        item.selected = false;
      }
    });
    this.setState({
      colorMenu: [...colorMenu],
      colorType: obj.key,
    });
  };

  render() {
    const { imgObject, colorMenu, colorType } = this.state;
    const {
      searchObj: { portfolioName, beginDate, endDate },
      list,
    } = this.props;
    let imgUrl;
    switch (colorType) {
      case 'darkBlue':
        imgUrl = headerDarkBlue;
        break;
      case 'red':
        imgUrl = headerRed;
        break;
      default:
        imgUrl = header;
    }
    return (
      <>
        {this.props.type == 'main' ? (
          <div className={style.operateCls}>
            <div className={style.colorMenu}>
              选择模板颜色:
              {colorMenu.map((item, index) => {
                return <img key={index} onClick={() => this.colorChange(item)} src={item.selected ? imgObject[`${item.key}ImgSelect`] : imgObject[`${item.key}Img`]} />;
              })}
            </div>
            <PrimaryC title='导出' loading={this.state.exportLoading} disabled={!list?.length} onClick={() => this.onExportpdf()} style={{ margin: '10px 20px' }} />
          </div>
        ) : null}
        <div style={{ height: this.props.type == 'main' ? 'calc(100vh - 301px)' : 'auto', overflowY: 'auto', marginTop: this.props.type == 'main' ? 'inherit' : '16px' }}>
          {this.props.type == 'main' ? (
            <div className={style.reportHeader} id='performanceAnalysisHeader' style={{ width: this.props.type == 'main' ? '920px' : 'auto', minWidth: '920px' }}>
              <img src={imgUrl} width='100%' height='100%' />
              <div className={colorType == 'default' ? style.reportTitle : colorType == 'red' ? style.reportTitleRed : style.reportTitleDarkBlue}>绩效分析报告</div>
              <div className={style.reportPT}>
                <span className={style.reportProduct}>产品名称：{portfolioName}</span>
                <span className={style.reportTime}>
                  {beginDate} ~ {endDate}
                </span>
              </div>
            </div>
          ) : null}
          <div id='performanceAnalysisReportId' style={{ width: this.props.type == 'main' ? '920px' : 'auto', margin: '0 auto', minWidth: '920px' }}>
            {this.renderContent()}
          </div>
        </div>
      </>
    );
  }
}
export default connect(({ profitOverviewM }) => ({
  profitOverviewM,
}))(DrawBoardC);
